<?php

class wei
{
    private $route;
    
    public function run()
    {
        $this->testOrm();
        $this->route();
        try {
            $this->dispatch();
        } catch(\Exception $e) {
            throw new $e;
        }
    }
    
    public function route()
    {
        $this->route = new wei\core\Route();
        $this->route->init();
    }
    
    public function dispatch()
    {
        $controller_name = ucwords($this->route->controller).'Controller';
        $action_name     = $this->route->action.'Action';
        $group           = $this->route->group;
        $class_name      = "app\\{$group}\module\controller\\{$controller_name}";
        $methods         = get_class_methods($class_name);
        if (!in_array($action_name,$methods,true))
        {
            throw new \Exception("系统错误");
        }
        
        //将 route 信息注入到controller 控制器
        $reflectedClass = new \ReflectionClass('wei\core\Controller');
        $reflectedProperty = $reflectedClass->getProperty('route');
        $reflectedProperty->setAccessible(true);
        $reflectedProperty->setValue($this->route);
        
        $handler = new $class_name;
        
        //前置拦截器
        $this->interceptorHandle('preHandle');
        if (in_array("_beforeAction",$methods))
        {
            call_user_func([$handler,'_beforeAction']);
        }
        
        $handler->{$action_name}();
        
        //后置拦截器
        if (in_array("_afterAction",$methods))
        {
            call_user_func([$handler,'_afterAction']);
        }
        $this->interceptorHandle('postHandle');
    }
    
    /**
     * 异常处理
     *
     * @param object $exception 异常类对象
     *
     * @return mixed
     */
    public static function exceptionHandler($exception)
    {
        if ($exception instanceof \wei\core\BaseException)
        {
            $exception->errorMessage();
        }
        else
        {
            $new_exception = new \wei\core\BaseException("未知错误",2000,$exception);
            $new_exception->errorMessage();
        }
    }
    
    /**
     * 错误处理
     * @param string $err_level    错误级别
     * @param string $err_str      错误描述
     * @param string $err_file     错误文件
     * @param string $err_line     错误所在行数
     * @return mixed
     */
    public static function errorHandler($err_level='',$err_str='',$err_file='',$err_line='')
    {
        $err = '错误级别:'.$err_level.'|错误描述：'.$err_str;
        $err .= '|错误所在文件:'.$err_file.'|错误所在行号:'.$err_line."\r\n";
        echo  $err;
        file_put_contents(_APP.'log.text',$err,FILE_APPEND);
    }
    
    /**
     * 拦截器处理逻辑
     *
     * @param string $type 拦截器类型 preHandle | postHandle
     *
     * @return mixed
     */
    public function interceptorHandle($type)
    {
        $interceptor_arr = $GLOBALS['_config']['interceptor'];
        if ($type == 'postHandle')
        {
            $interceptor_arr = array_reverse($interceptor_arr);
        }
        
        $path = "{$this->route->group}/{$this->route->controller}/{$this->route->action}";
        foreach($interceptor_arr as $k=>$v)
        {
            if ( ($v === '*') || preg_match($v,$path) > 0)
            {
                $interceptor = new $k;
                $interceptor->{$type}();
            }
        }
    }
    
    /**
     * 引入orm类测试
     */
    public function testOrm()
    {
        $capsule = new Illuminate\Database\Capsule\Manager();
        $capsule ->addConnection(
            [
                'driver'    => 'mysql',
                'host'      => 'localhost',
                'database'  => 'easyswoole',
                'username'  => 'root',
                'password'  => '521lwj',
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => 'easy_',
            ]
        );
        $capsule->bootEloquent();
    }
}

